package com.dzx.currentency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月20日 10:58:29
 */

/**
 * 一般用于控制同一时刻运行的线程数量
 *             |      |
 *  ---------|-----|---------
 *             |      |
 *  ---------|-----|---------
 *             |      |
 */
@Slf4j
public class SemaphoreExample1 {


    private static int threadCount = 20;

    public static void main(String[] args) throws InterruptedException {

        ExecutorService service = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            service.execute(() -> {
                try {
                    //semaphore.acquire();  每次拿一个许可证
                    //semaphore.acquire(3); 每次拿三个许可证
                      semaphore.tryAcquire(3);
                      semaphore.tryAcquire(1,TimeUnit.SECONDS); //尝试一秒之内获取许可
                    semaphore.tryAcquire(3,1,TimeUnit.SECONDS);
                    if(semaphore.tryAcquire()) { //尝试获取许可证 ，没有获取到直接将当前线程丢弃

                        test(threadNum);
                        semaphore.release();
                    }else {
                        log.info(Thread.currentThread().getName()+"我没有拿到许可证，┭┮﹏┭┮");
                    }
                } catch (InterruptedException e) {
                    log.error("exception", e);
                }
            });
        }

        service.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
        log.info("{}", threadNum);
        Thread.sleep(1000);
    }
}
